package com.keur.money.data.dv

import com.google.gson.Gson
import com.keur.money.config.KeurConfigs
import com.keur.money.data.dv.hepler.DvBatHelper
import com.keur.money.data.dv.hepler.DvHelper
import com.keur.money.data.dv.hepler.DvIMSHelper
import com.keur.money.utils.helper.SharedHelper

class DvDataMode() {

    val product = KeurConfigs.KEUR_APPNAME
    val token = SharedHelper.getKeurSPString(SharedHelper.KEUR_SPKEY.KEUR_TOKEN)
    private fun toFormat1(path: String, fetchData: () -> String?): String? {
        if (!formatJson(path)) return null
        val content = fetchData()?:""

        // TODO: 加密操作
//        val encrypted: String = EKHAesTool.encryptDefault(content)
//        return encrypted

        // TODO: 不加密
        return content
    }

    private fun toFormat2(path: String, key: String, fetchData: () -> String?): String? {
        if (!formatJson(path)) return null
        val data = fetchData() ?: return null
        val params = baseJson(path).apply { put(key, data) }
        val content = Gson().toJson(params).trim()

        // TODO: 加密操作
//        val encrypted: String = EKHAesTool.encryptDefault(content)
//        return encrypted

        // TODO: 不加密
        return content
    }

    private fun formatJson(path: String) = listOf(product, token, path).all { it.isNotBlank() }

    private fun baseJson(path: String) = hashMapOf<String, Any>(
        "path" to path.replace("/", ""),
        "token" to token,
        "product" to product
    )

    /**
     * Device
     */
    fun getDvData(path: String) = toFormat1(path) {
        DvHelper().gKeurDvData()
    }

    /**
     * SMS
     */
    fun getDvIMSData(path: String) = toFormat1(path) {
        DvIMSHelper().gKeurDvIMSData()
    }

    /**
     * hardware
     */
    fun getDvHdData(path: String) = toFormat2(path, "deviceHardwareGzip") {
        DvHelper().gKeurHdData()
    }

    /**
     * battery
     */
    fun getDvBatData(path: String, onResult: (String?) -> Unit) {
        DvBatHelper(onResult = { bd ->
            val result = toFormat2(path, "deviceBatteryGzip") { bd }
            onResult.invoke(result)
        }).start()
    }

    /**
     * wifi
     */
    fun getDvNetworkData(path: String) = toFormat2(path, "deviceWifiGzip") {
        DvHelper().gKeurNetwork()
    }

    /**
     * storage
     */
    fun getDvStoData(path: String) = toFormat2(path, "deviceStorageGzip") {
        DvHelper().gKeurSto()
    }

    /**
     * AppList
     */
    fun getDvAplData(path: String) = toFormat2(path, "appListGzip") {
        DvHelper().gKeurAplData()
    }
}